import React, { useState, useRef, useEffect } from 'react';
import { Button, Space, message } from 'antd';
import { Link } from 'react-router-dom';
import { ArrowLeftOutlined, CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons';
import { Light as SyntaxHighlighter } from 'react-syntax-highlighter';
import json from 'react-syntax-highlighter/dist/esm/languages/hljs/json';
import { github } from 'react-syntax-highlighter/dist/esm/styles/hljs';

SyntaxHighlighter.registerLanguage('json', json);

const JsonTool = () => {
  const [inputJson, setInputJson] = useState('');
  const [validationMessage, setValidationMessage] = useState('');
  const [validationStatus, setValidationStatus] = useState('');
  const [highlightedJson, setHighlightedJson] = useState('');
  const [collapsedNodes, setCollapsedNodes] = useState(new Set());
  const editorRef = useRef(null);
  const highlighterRef = useRef(null);

  // 解析JSON结构
  const parseJsonStructure = (jsonStr) => {
    try {
      const lines = jsonStr.split('\n');
      const structure = new Map();
      const stack = [];
      
      lines.forEach((line, index) => {
        const lineNum = index + 1;
        const trimmed = line.trim();
        
        // 检测是否是对象或数组的开始
        if (trimmed.endsWith('{') || trimmed.endsWith('[')) {
          stack.push(lineNum);
        }
        // 检测是否是对象或数组的结束
        else if (trimmed === '}' || trimmed === ']' || trimmed.endsWith('},') || trimmed.endsWith('],')) {
          const startLine = stack.pop();
          if (startLine) {
            structure.set(startLine, lineNum);
          }
        }
      });
      
      return structure;
    } catch (e) {
      return new Map();
    }
  };

  // 切换节点展开/收缩
  const toggleNode = (lineNumber) => {
    try {
      const structure = parseJsonStructure(inputJson);
      const endLine = structure.get(lineNumber);
      
      if (endLine) {
        const newCollapsed = new Set(collapsedNodes);
        if (newCollapsed.has(lineNumber)) {
          newCollapsed.delete(lineNumber);
        } else {
          newCollapsed.add(lineNumber);
        }
        setCollapsedNodes(newCollapsed);
      }
    } catch (e) {
      console.error('Toggle node failed:', e);
    }
  };

  // 计算行号区域所需的最小宽度
  const getLineNumbersWidth = () => {
    const lines = inputJson.split('\n');
    const maxDigits = lines.length.toString().length;
    // 每个数字大约10px宽，加上padding和图标的空间
    return Math.max(50, maxDigits * 10 + 40) + 'px';
  };

  // 生成行号和折叠图标
  const renderLineNumbers = () => {
    const lines = inputJson.split('\n');
    const structure = parseJsonStructure(inputJson);
    const width = getLineNumbersWidth();
    
    return (
      <div className="line-numbers-inner" style={{ width }}>
        {lines.map((line, index) => {
          const lineNum = index + 1;
          const isCollapsible = structure.has(lineNum);
          const isCollapsed = collapsedNodes.has(lineNum);
          
          return (
            <div key={lineNum} className="line-number">
              {isCollapsible && (
                <span className="collapse-icon" onClick={() => toggleNode(lineNum)}>
                  {isCollapsed ? <CaretRightOutlined /> : <CaretDownOutlined />}
                </span>
              )}
              <span className="number">{lineNum}</span>
            </div>
          );
        })}
      </div>
    );
  };

  // 处理折叠后的显示
  const getVisibleContent = () => {
    if (collapsedNodes.size === 0) return highlightedJson;
    
    const lines = highlightedJson.split('\n');
    const structure = parseJsonStructure(highlightedJson);
    const visibleLines = [];
    
    for (let i = 0; i < lines.length; i++) {
      const lineNum = i + 1;
      if (collapsedNodes.has(lineNum)) {
        // 添加当前行
        visibleLines.push(lines[i]);
        // 跳过被折叠的内容
        const endLine = structure.get(lineNum);
        if (endLine) {
          i = endLine - 1; // -1 因为循环会 i++
        }
      } else {
        visibleLines.push(lines[i]);
      }
    }
    
    return visibleLines.join('\n');
  };

  const handleScroll = (e) => {
    if (highlighterRef.current) {
      highlighterRef.current.scrollTop = e.target.scrollTop;
      highlighterRef.current.scrollLeft = e.target.scrollLeft;
      
      const lineNumbers = document.querySelector('.line-numbers');
      if (lineNumbers) {
        lineNumbers.scrollTop = e.target.scrollTop;
      }
    }
  };

  useEffect(() => {
    try {
      if (inputJson.trim()) {
        JSON.parse(inputJson); // 只验证格式
        setHighlightedJson(inputJson);
      } else {
        setHighlightedJson('');
      }
    } catch (e) {
      setHighlightedJson(inputJson);
    }
  }, [inputJson]);

  useEffect(() => {
    // 更新行号区域宽度
    const width = getLineNumbersWidth();
    document.documentElement.style.setProperty('--line-numbers-width', width);
  }, [inputJson]);

  const formatJson = () => {
    if (!inputJson.trim()) {
      setValidationMessage('');
      setValidationStatus('');
      return;
    }

    try {
      const parsed = JSON.parse(inputJson);
      const formatted = JSON.stringify(parsed, null, 2);
      if (editorRef.current) {
        editorRef.current.textContent = formatted;
        setInputJson(formatted);
        setHighlightedJson(formatted);
      }
      setCollapsedNodes(new Set()); // 重置折叠状态
      setValidationMessage('JSON格式正确');
      setValidationStatus('success');
    } catch (e) {
      setValidationMessage(e.message);
      setValidationStatus('error');
    }
  };

  const compressJson = () => {
    if (!inputJson.trim()) {
      setValidationMessage('');
      setValidationStatus('');
      return;
    }

    try {
      const parsed = JSON.parse(inputJson);
      const compressed = JSON.stringify(parsed);
      if (editorRef.current) {
        editorRef.current.textContent = compressed;
        setInputJson(compressed);
        setHighlightedJson(compressed);
      }
      setCollapsedNodes(new Set()); // 重置折叠状态
      setValidationMessage('JSON压缩成功');
      setValidationStatus('success');
    } catch (e) {
      setValidationMessage(e.message);
      setValidationStatus('error');
    }
  };

  const clearAll = () => {
    setInputJson('');
    setValidationMessage('');
    setValidationStatus('');
    setHighlightedJson('');
    setCollapsedNodes(new Set());
    if (editorRef.current) {
      editorRef.current.textContent = '';
    }
  };

  const copyJson = () => {
    if (inputJson) {
      navigator.clipboard.writeText(inputJson);
      message.success('已复制到剪贴板');
    }
  };

  const handleInput = (e) => {
    const content = e.currentTarget.textContent || '';
    setInputJson(content);
  };

  return (
    <div className="tool-container">
      <div className="tool-header">
        <Link to="/" className="back-button">
          <ArrowLeftOutlined />
          返回工具箱
        </Link>
        <div className="tool-title">JSON格式化</div>
      </div>
      
      <div className="tool-content json-tool">
        <div className="json-card">
          <div className="button-group">
            <Space size="middle" className="button-space">
              <Button 
                type="primary" 
                onClick={formatJson}
                className="format-btn"
              >
                格式化校验
              </Button>
              <Button 
                type="primary" 
                onClick={compressJson}
                className="compress-btn"
              >
                压缩
              </Button>
              <Button 
                type="primary" 
                onClick={copyJson}
                className="copy-btn"
              >
                复制
              </Button>
              <Button 
                onClick={clearAll}
                className="clear-btn"
              >
                清空
              </Button>
            </Space>
          </div>

          <div className="input-section">
            <div className="json-editor-wrapper">
              <div className="line-numbers">
                {renderLineNumbers()}
              </div>
              <div
                ref={editorRef}
                className="json-editor"
                contentEditable={true}
                onInput={handleInput}
                onScroll={handleScroll}
                spellCheck={false}
                data-placeholder="请输入要格式化的JSON"
              />
              <div className="json-highlight-wrapper" ref={highlighterRef}>
                <SyntaxHighlighter
                  language="json"
                  style={github}
                  className="json-highlight"
                  showLineNumbers={false}
                  wrapLines={true}
                >
                  {getVisibleContent()}
                </SyntaxHighlighter>
              </div>
            </div>
          </div>

          {validationMessage && (
            <div className={`validation-message ${validationStatus}`}>
              {validationMessage}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default JsonTool;
